import Vue from "vue";
import Vuex from "vuex";

// 获取token|设置token|删除token的函数
import { getToken, setToken, removeToken } from "@/utils/auth";
import { anyRoutes, resetRouter, asyncRoutes, constantRoutes } from "@/router";
import router from "@/router";
import cloneDeep from "lodash/cloneDeep";
import { reqGetCode, reqUserLogin, reqLogout, reqGetInfo } from "@/api/user";

Vue.use(Vuex);
const getDefaultState = () => {
  return {
    token: getToken(),
    code: "",
    userInfo: {},
    userName: "",
  };
};
//定义一个函数：两个数组进行对比，对比出当前用户到底显示哪些异步路由
const computedAsyncRoutes = (asyncRoutes, routes) => {
  //过滤出当前用户【超级管理|普通员工】需要展示的异步路由
  return asyncRoutes.filter((item) => {
    //数组当中没有这个元素返回索引值-1，如果有这个元素返回的索引值一定不是-1
    // console.log(routes, item.path, routes.indexOf(item.path), "cs")
    if (routes.indexOf(item.path) != -1) {
      //递归:别忘记还有2、3、4、5、6级路由
      if (item.children && item.children.length) {
        console.log(item.children, "erz");
        item.children = computedAsyncRoutes(item.children, routes);
      }
      return true;
    }
  });
};
export default new Vuex.Store({
  state: getDefaultState(),
  mutations: {
    GETCODE(state, code) {
      state.code = code;
    },
    SET_USER: (state, data) => {
      state.token = data.token;
      // state.userInfo = data.user
      // state.userName = data.user.userName
    },
    SET_USERINFO: (state, data) => {
      state.userName = data.user;
    },
    //重置state
    RESET_STATE: (state) => {
      Object.assign(state, getDefaultState());
    },
    //最终计算出的异步路由
    SET_RESULTASYNCROUTES: (state, asyncRoutes) => {
      //vuex保存当前用户的异步路由，注意，一个用户需要展示完成路由：常量、异步、任意路由
      // console.log(asyncRoutes, "router")
      state.resultAsyncRoutes = asyncRoutes;
      //计算出当前用户需要展示所有路由
      state.resultAllRputes = constantRoutes.concat(
        state.resultAsyncRoutes,
        anyRoutes
      );
      setToken("resultAsyncRoutes", state.resultAsyncRoutes);
      setToken("resultAllRputes", state.resultAllRputes);
      // console.log(state.resultAsyncRoutes, "resultAsyncRoutes")
      // console.log(state.resultAllRputes, "resultAllRputes")
      //给路由器添加新的路由
      // router.addRoutes(state.resultAllRputes)
      for (let x of state.resultAllRputes) {
        router.addRoute(x);
      }
    },
  },
  actions: {
    async getCode({ commit }) {
      let result = await reqGetCode();
      if (result.resultCode === 200) {
        commit("GETCODE", result.data);
        return result.data;
      } else {
        return Promise.reject(new Error("faile"));
      }
    },
    async login({ commit, dispatch }, userInfo) {
      let result = await reqUserLogin(userInfo);
      console.log(result, "login");
      //注意：当前登录请求现在使用mock数据，mock数据code是20000
      if (result.resultCode == 200) {
        //vuex存储token
        commit("SET_USER", result.data);
        //本地持久化存储token
        setToken("token", result.data.token);
        // localStorage.setItem("token", result.data.token);
        setToken("userInfo", JSON.stringify(result.data.user));
        // dispatch("getInfo");
        return "ok";
      } else {
        return Promise.reject(result.msg);
      }
    },
    async logout({ commit }) {
      return new Promise((resolve, reject) => {
        reqLogout()
          .then(() => {
            removeToken("token"); // must remove  token  first
            removeToken("userInfo");
            resetRouter();
            // resetRouter()
            commit("RESET_STATE");
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // remove token
    // resetToken({ commit }) {
    //   return new Promise((resolve) => {
    //     removeToken("token"); // must remove  token  first
    //     removeToken("userInfo");
    //     resetRouter();
    //     commit("RESET_STATE");
    //     resolve();
    //   });
    // },
  },
  getters: {
    name: (state) => state.userName,
  },
});

// export default {
//   namespaced: true,
//   state,
//   mutations,
//   actions
// }
